import Toast from 'tdesign-miniprogram/toast/index';
import { areaData } from '../../../config/index';
import request from '../../../utils/request';
// import { resolveAddress, rejectAddress } from './util';

const innerPhoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$';
const innerNameReg = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$';


Page({
  externalClasses: ['theme-wrapper-class'],
  data: {
    detailAddress: '',
    name: '',
    mobile: '',
    company: '',
    userType: 1,
    submitActive: false,
    visible: false,
    areaData: areaData,
    provinceCode: '',
    provinceName: '',
    cityCode: '',
    cityName: '',
    districtCode: '',
    districtName: '',
  },
  privateData: {
    verifyTips: '',
  },
  onLoad(options) {
    // const { userType } = options;
    // this.setData({ userType: userType });
    wx.hideHomeButton();
  },

  registerBusiness() {
    this.setData({ userType: 1 });

  },
  registerappraiser() {
    this.setData({ userType: 0 });
  },

  adminLogin() {
    wx.navigateTo({
      url: '/pages/admin/login/index'
    });
  },

  hasSava: false,

  onInputValue(e) {
    console.log("aaaaaaaaaa")
    const { item } = e.currentTarget.dataset;
    if (item === 'address') {
      const { selectedOptions = [] } = e.detail;
      this.setData(
        {
          'provinceCode': selectedOptions[0].value,
          'provinceName': selectedOptions[0].label,
          'cityName': selectedOptions[1].label,
          'cityCode': selectedOptions[1].value,
          'districtCode': selectedOptions[2].value,
          'districtName': selectedOptions[2].label,
          areaPickerVisible: false,
        },
        () => {
          const { isLegal, tips } = this.onVerifyInputLegal();
          this.setData({
            submitActive: isLegal,
          });
          this.privateData.verifyTips = tips;
        },
      );
    } else {
      const { value = '' } = e.detail;
      this.setData(
        {
          [`${item}`]: value,
        },
        () => {
          const { isLegal, tips } = this.onVerifyInputLegal();
          this.setData({
            submitActive: isLegal,
          });
          this.privateData.verifyTips = tips;
        },
      );
    }
  },
  onPickArea() {
    this.setData({ areaPickerVisible: true });
  },

  onVerifyInputLegal() {
    const { name, mobile, detailAddress, districtName } = this.data;
    const prefixPhoneReg = String(this.properties.phoneReg || innerPhoneReg);
    const prefixNameReg = String(this.properties.nameReg || innerNameReg);
    const nameRegExp = new RegExp(prefixNameReg);
    const phoneRegExp = new RegExp(prefixPhoneReg);

    if (!name || !name.trim()) {
      return {
        isLegal: false,
        tips: '请填写姓名',
      };
    }
    // if (!nameRegExp.test(name)) {
    //   return {
    //     isLegal: false,
    //     tips: '姓名仅支持输入中文、英文（区分大小写）、数字',
    //   };
    // }
    if (!mobile || !mobile.trim()) {
      return {
        isLegal: false,
        tips: '请填写手机号',
      };
    }
    if (!phoneRegExp.test(mobile)) {
      return {
        isLegal: false,
        tips: '请填写正确的手机号',
      };
    }
    if (this.data.userType == 1) {
      if (!districtName || !districtName.trim()) {
        return {
          isLegal: false,
          tips: '请选择省市区信息',
        };
      }
      if (!detailAddress || !detailAddress.trim()) {
        return {
          isLegal: false,
          tips: '请完善详细地址',
        };
      }
      if (detailAddress && detailAddress.trim().length > 50) {
        return {
          isLegal: false,
          tips: '详细地址不能超过50个字符',
        };
      }
    }
    return {
      isLegal: true,
      tips: '添加成功',
    };
  },

  builtInSearch({ code, name }) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting[code] === false) {
            wx.showModal({
              title: `获取${name}失败`,
              content: `获取${name}失败，请在【右上角】-小程序【设置】项中，将【${name}】开启。`,
              confirmText: '去设置',
              confirmColor: '#FA550F',
              cancelColor: '取消',
              success(res) {
                if (res.confirm) {
                  wx.openSetting({
                    success(settinRes) {
                      if (settinRes.authSetting[code] === true) {
                        resolve();
                      } else {
                        console.warn('用户未打开权限', name, code);
                        reject();
                      }
                    },
                  });
                } else {
                  reject();
                }
              },
              fail() {
                reject();
              },
            });
          } else {
            resolve();
          }
        },
        fail() {
          reject();
        },
      });
    });
  },

  onSearchAddress() {
    this.builtInSearch({ code: 'scope.userLocation', name: '地址位置' }).then(() => {
      //   wx.chooseLocation({
      //     success: (res) => {
      //       if (res.name) {
      //         this.triggerEvent('addressParse', {
      //           address: res.address,
      //           name: res.name,
      //           latitude: res.latitude,
      //           longitude: res.longitude,
      //         });
      //       } else {
      //         Toast({
      //           context: this,
      //           selector: '#t-toast',
      //           message: '地点为空，请重新选择',
      //           icon: '',
      //           duration: 1000,
      //         });
      //       }
      //     },
      //     fail: function (res) {
      //       console.warn(`wx.chooseLocation fail: ${JSON.stringify(res)}`);
      //       if (res.errMsg !== 'chooseLocation:fail cancel') {
      //         Toast({
      //           context: this,
      //           selector: '#t-toast',
      //           message: '地点错误，请重新选择',
      //           icon: '',
      //           duration: 1000,
      //         });
      //       }
      //     },
      //   });
    });
  },
  formSubmit() {
    var that = this;
    const { submitActive } = this.data;
    const { isLegal, tips } = this.onVerifyInputLegal();
    if (!isLegal) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: tips,
        icon: '',
        duration: 1000,
      });
      return;
    }
    if (!submitActive) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: this.privateData.verifyTips,
        icon: '',
        duration: 1000,
      });
      return;
    }
    var url = "/car/user/login/register"
    var data = {
      address: this.data.detailAddress,
      city: this.data.cityCode,
      cityName: this.data.cityName,
      company: this.data.company,
      contacts: this.data.name,
      mobile: this.data.mobile,
      name: this.data.name,
      openid: wx.getStorageSync('openid'),
      province: this.data.provinceCode,
      provinceName: this.data.provinceName,
      userType: this.data.userType,
      county: this.data.districtCode,
      countyName: this.data.districtName
    }
    request.post(url, data, function (res) {
      if (res.code == 0) {
        that.hasSava = true;
        getApp().globalData.token = res.data.token;
        getApp().globalData.userInfo = res.data.user;
        getApp().globalData.openid = res.data.user.openid;
        console.log("save user", getApp().globalData.userInfo)
        wx.setStorageSync('token', getApp().globalData.token);
        wx.setStorageSync('openid', res.data.user.openid);
        wx.setStorageSync('userInfo', JSON.stringify(getApp().globalData.userInfo));

        wx.navigateBack({ delta: 1 });
      }
    })

    // this.hasSava = true;
    // getApp().globalData.token = "token";
    // getApp().globalData.userInfo = {
    //   userId: 1,
    //   openId: 'openId',
    //   userType: this.data.userType,
    //   phone: this.data.phone,
    //   name: this.data.name,
    //   marginPrice: 3000
    // };
    // console.log("save user", getApp().globalData.userInfo)
    // wx.setStorageSync('token', getApp().globalData.token);
    // wx.setStorageSync('userInfo', JSON.stringify(getApp().globalData.userInfo));


    // resolveAddress({
    //   saasId: '88888888',
    //   uid: `88888888205500`,
    //   authToken: null,
    //   id: locationState.addressId,
    //   addressId: locationState.addressId,
    //   phone: locationState.phone,
    //   name: locationState.name,
    //   countryName: locationState.countryName,
    //   countryCode: locationState.countryCode,
    //   provinceName: locationState.provinceName,
    //   provinceCode: locationState.provinceCode,
    //   cityName: locationState.cityName,
    //   cityCode: locationState.cityCode,
    //   districtName: locationState.districtName,
    //   districtCode: locationState.districtCode,
    //   detailAddress: locationState.detailAddress,
    //   isDefault: locationState.isDefault === 1 ? 1 : 0,
    //   addressTag: locationState.addressTag,
    //   latitude: locationState.latitude,
    //   longitude: locationState.longitude,
    //   storeId: null,
    // });


  }
});
